package com.naodong.shenluntiku.mvp.view.webView;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.github.lzyzsd.jsbridge.BridgeWebView;

/**
 * Created by hujie on 17/5/12.
 */

public class TKWebView extends BridgeWebView {


    TKWebViewClient webViewClient;

    TKWebViewListener tkWebViewListener;

    public void setTkWebViewListener(TKWebViewListener tkWebViewListener) {
        this.tkWebViewListener = tkWebViewListener;
        webViewClient.setTkWebViewListener(tkWebViewListener);
    }

    public TKWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TKWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public TKWebView(Context context) {
        super(context);
        init();
    }


    private void init() {
        WebSettings settings = this.getSettings();


        settings.setDomStorageEnabled(true);

        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
        settings.setLoadWithOverviewMode(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        String userAgentString = settings.getUserAgentString();
        settings.setUserAgentString(userAgentString + " " + "shenluntikuApp");

        webViewClient = new TKWebViewClient(this);
        this.setWebViewClient(webViewClient);
        this.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (tkWebViewListener != null) {
                    tkWebViewListener.onProgressChanged(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (tkWebViewListener != null) {
                    tkWebViewListener.setReceiveTitle(title);
                }
                super.onReceivedTitle(view, title);
            }


        });


        this.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            if (tkWebViewListener != null) {
                tkWebViewListener.download(url);
            }
        });

    }
}
